document.addEventListener('DOMContentLoaded', function() {
    // DOM 元素引用
    const messagesContainer = document.getElementById('messagesContainer');
    const userInput = document.getElementById('userInput');
    const sendBtn = document.getElementById('sendBtn');
    const clearChatBtn = document.getElementById('clearChatBtn');
    const settingsToggleBtn = document.getElementById('settingsToggleBtn');
    const settingsPanel = document.getElementById('settingsPanel');
    const resetSettingsBtn = document.getElementById('resetSettingsBtn');
    
    // 模型参数元素
    const modelSelect = document.getElementById('modelSelect');
    const temperatureRange = document.getElementById('temperatureRange');
    const temperatureValue = document.getElementById('temperatureValue');
    const maxTokensRange = document.getElementById('maxTokensRange');
    const maxTokensValue = document.getElementById('maxTokensValue');
    const topPRange = document.getElementById('topPRange');
    const topPValue = document.getElementById('topPValue');
    const topKRange = document.getElementById('topKRange');
    const topKValue = document.getElementById('topKValue');
    const repetitionPenaltyRange = document.getElementById('repetitionPenaltyRange');
    const repetitionPenaltyValue = document.getElementById('repetitionPenaltyValue');
    const doSampleSwitch = document.getElementById('doSampleSwitch');
    
    // 消息历史
    let messageHistory = [];
    
    // 是否正在生成回复
    let isGenerating = false;
    
    // 默认参数
    let defaultSettings = {
        "max_tokens": 1024,
        "stream": false,
        "do_sample": true,
        "repetition_penalty": 1.00,
        "temperature": 0.7,
        "top_p": 0.9,
        "top_k": 40,
        "model": "qwen"
    };
    
    // 初始化
    initializeApp();
    
    function initializeApp() {
        // 从API获取默认设置
        fetch('/api/settings')
            .then(response => response.json())
            .then(settings => {
                defaultSettings = settings;
                updateUIWithSettings(settings);
            })
            .catch(error => console.error('Failed to load settings:', error));
        
        // 事件监听
        userInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        sendBtn.addEventListener('click', sendMessage);
        clearChatBtn.addEventListener('click', clearChat);
        settingsToggleBtn.addEventListener('click', toggleSettings);
        resetSettingsBtn.addEventListener('click', resetSettings);
        
        // 参数滑块事件
        setupRangeListener(temperatureRange, temperatureValue);
        setupRangeListener(maxTokensRange, maxTokensValue);
        setupRangeListener(topPRange, topPValue);
        setupRangeListener(topKRange, topKValue);
        setupRangeListener(repetitionPenaltyRange, repetitionPenaltyValue);
    }
    
    function setupRangeListener(rangeElement, valueElement) {
        rangeElement.addEventListener('input', function() {
            valueElement.textContent = this.value;
        });
    }
    
    function updateUIWithSettings(settings) {
        // 更新UI元素的值
        modelSelect.value = settings.model || 'qwen';
        temperatureRange.value = settings.temperature;
        temperatureValue.textContent = settings.temperature;
        maxTokensRange.value = settings.max_tokens;
        maxTokensValue.textContent = settings.max_tokens;
        topPRange.value = settings.top_p;
        topPValue.textContent = settings.top_p;
        topKRange.value = settings.top_k;
        topKValue.textContent = settings.top_k;
        repetitionPenaltyRange.value = settings.repetition_penalty;
        repetitionPenaltyValue.textContent = settings.repetition_penalty;
        doSampleSwitch.checked = settings.do_sample;
    }
    
    function getCurrentSettings() {
        // 获取当前UI设置的参数
        return {
            model: modelSelect.value,
            temperature: parseFloat(temperatureRange.value),
            max_tokens: parseInt(maxTokensRange.value),
            top_p: parseFloat(topPRange.value),
            top_k: parseInt(topKRange.value),
            repetition_penalty: parseFloat(repetitionPenaltyRange.value),
            do_sample: doSampleSwitch.checked,
            stream: false
        };
    }
    
    function resetSettings() {
        // 重置为默认设置
        updateUIWithSettings(defaultSettings);
    }
    
    function toggleSettings() {
        // 切换设置面板显示/隐藏
        settingsPanel.classList.toggle('active');
    }
    
    function sendMessage() {
        // 获取用户输入
        const message = userInput.value.trim();
        if (message === '' || isGenerating) return;
        
        // 添加用户消息到界面
        addMessage('user', message);
        
        // 清空输入框
        userInput.value = '';
        
        // 更新消息历史
        messageHistory.push({
            role: 'user',
            content: message
        });
        
        // 生成回复
        generateResponse(message);
    }
    
    function generateResponse(prompt) {
        // 显示加载指示器
        const loadingIndicator = addLoadingIndicator();
        
        // 设置生成状态
        isGenerating = true;
        
        // 获取当前设置
        const settings = getCurrentSettings();
        
        // 准备请求数据
        const requestData = {
            ...settings,
            prompt: prompt
        };
        
        // 发送API请求
        fetch('/api/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`API Error: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            // 移除加载指示器
            if (loadingIndicator) {
                loadingIndicator.remove();
            }
            
            // 处理响应
            if (data.error) {
                addMessage('ai', `错误: ${data.error}`);
            } else {
                const reply = data.text || data.response || data.generated_text || '没有返回内容';
                addMessage('ai', reply);
                
                // 更新消息历史
                messageHistory.push({
                    role: 'assistant',
                    content: reply
                });
            }
        })
        .catch(error => {
            console.error('API Request Error:', error);
            
            // 移除加载指示器
            if (loadingIndicator) {
                loadingIndicator.remove();
            }
            
            // 显示错误消息
            addMessage('ai', `请求出错: ${error.message}`);
        })
        .finally(() => {
            // 重置生成状态
            isGenerating = false;
        });
    }
    
    function addMessage(role, content) {
        // 创建消息元素
        const messageDiv = document.createElement('div');
        messageDiv.className = `message message-${role}`;
        
        // 创建消息内容元素
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        
        // 使用Markdown渲染内容
        try {
            contentDiv.innerHTML = marked.parse(content);
        } catch (e) {
            contentDiv.textContent = content;
        }
        
        // 添加到消息元素
        messageDiv.appendChild(contentDiv);
        
        // 添加到消息容器
        messagesContainer.appendChild(messageDiv);
        
        // 滚动到底部
        scrollToBottom();
    }
    
    function addLoadingIndicator() {
        // 创建加载指示器
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message message-ai';
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        
        const typingIndicator = document.createElement('div');
        typingIndicator.className = 'typing-indicator';
        typingIndicator.innerHTML = '思考中<div class="dot"></div><div class="dot"></div><div class="dot"></div>';
        
        contentDiv.appendChild(typingIndicator);
        messageDiv.appendChild(contentDiv);
        messagesContainer.appendChild(messageDiv);
        
        // 滚动到底部
        scrollToBottom();
        
        return messageDiv;
    }
    
    function clearChat() {
        // 清空消息历史
        messageHistory = [];
        
        // 清空消息容器
        messagesContainer.innerHTML = '';
        
        // 添加欢迎消息
        const welcomeDiv = document.createElement('div');
        welcomeDiv.className = 'welcome-message';
        welcomeDiv.innerHTML = '<h4>欢迎使用 Deepseek 智能对话</h4><p>请输入您的问题，开始对话吧！</p>';
        messagesContainer.appendChild(welcomeDiv);
    }
    
    function scrollToBottom() {
        // 滚动到聊天容器底部
        const chatContainer = document.getElementById('chatContainer');
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }
}); 